/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GenerateKB.java
 *
 * Created on 14/08/2010, 5:47:16 PM
 */

package utilities;
import com.hp.hpl.jena.ontology.OntModel;
import edu.stanford.smi.protege.model.KnowledgeBase;
import edu.stanford.smi.protege.model.Project;
import edu.stanford.smi.protegex.owl.model.OWLModel;
import java.net.URI;
import java.util.*;
import java.util.logging.*;
import java.io.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.*;



import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.dom4j.*;
import org.dom4j.io.*;


import com.hp.hpl.jena.query.*;
import com.hp.hpl.jena.rdf.arp.impl.Location;

import com.hp.hpl.jena.util.FileUtils;
import edu.stanford.smi.protege.model.*;
import edu.stanford.smi.protege.widget.*;
import edu.stanford.smi.protege.resource.*;

import edu.stanford.smi.protege.exception.OntologyLoadException;
import edu.stanford.smi.protege.model.KnowledgeBaseFactory;
import edu.stanford.smi.protegex.owl.model.OWLModel;
import edu.stanford.smi.protegex.owl.model.OWLNamedClass;
import edu.stanford.smi.protegex.owl.ProtegeOWL;
import edu.stanford.smi.protegex.owl.jena.JenaOWLModel;
import edu.stanford.smi.protegex.owl.model.OWLDatatypeProperty;
import edu.stanford.smi.protegex.owl.model.OWLObjectProperty;
import edu.stanford.smi.protegex.owl.model.RDFIndividual;
import edu.stanford.smi.protegex.owl.model.query.QueryResults;
import javax.swing.table.DefaultTableModel;
import jess.*;

/**
 *
 * @author ATuan
 */
public class GenerateKB extends javax.swing.JDialog {

    private Project prj;
    private KnowledgeBase kb;
    private String sLine;
    private String sPrjBase;
    private String sPrjFile;
    private String sProjectFullPath;

    private String sDataSetFilename;
    private long lNumberOfWillBeGenerated=0;
    private long xTimes=0;
    private long lNumOfLines=0;
    private static Logger theLogger =
	 Logger.getLogger(GenerateDataToKB.class.getName());
    private static FileHandler fileTxt;
    private static SimpleFormatter formatterTxt;
    private String sURI="http://www.tuannguyen.mobi/ontologies/2010/tinypbvc.owl#";
    private String sPreviousAddress="";

    private GenerateKBThread genThread=null;
    private Thread thr = null;

    /** Creates new form GenerateKB */
    public GenerateKB(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        try{
        formatterTxt = new SimpleFormatter();
        fileTxt = new FileHandler("GenerateKB.log",true);
        fileTxt.setFormatter(formatterTxt);
        theLogger.addHandler(fileTxt);
        }catch(Exception e){
            theLogger.severe(e.toString());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        KBfileTF = new javax.swing.JTextField();
        LoadKBBtn = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        GenerateKBBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        LoggingMessageTA = new javax.swing.JTextArea();
        jLabel3 = new javax.swing.JLabel();
        CountInstancesBtn = new javax.swing.JButton();
        ClassNameTF = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        NumberOfInstancesTF = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        ExitBtn = new javax.swing.JButton();
        NumberOfInstanceRequiredTF = new javax.swing.JTextField();
        PauseBtn = new javax.swing.JButton();
        StopBtn = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        StartIndexTF = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        StopIndexTF = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(placecommframework.PlaceCommFrameworkApp.class).getContext().getResourceMap(GenerateKB.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        KBfileTF.setText(resourceMap.getString("KBfileTF.text")); // NOI18N
        KBfileTF.setName("KBfileTF"); // NOI18N

        LoadKBBtn.setText(resourceMap.getString("LoadKBBtn.text")); // NOI18N
        LoadKBBtn.setName("LoadKBBtn"); // NOI18N
        LoadKBBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                LoadKBBtnMouseClicked(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        GenerateKBBtn.setText(resourceMap.getString("GenerateKBBtn.text")); // NOI18N
        GenerateKBBtn.setName("GenerateKBBtn"); // NOI18N
        GenerateKBBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                GenerateKBBtnMouseClicked(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        LoggingMessageTA.setColumns(20);
        LoggingMessageTA.setRows(5);
        LoggingMessageTA.setName("LoggingMessageTA"); // NOI18N
        jScrollPane1.setViewportView(LoggingMessageTA);

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        CountInstancesBtn.setText(resourceMap.getString("CountInstancesBtn.text")); // NOI18N
        CountInstancesBtn.setName("CountInstancesBtn"); // NOI18N
        CountInstancesBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                CountInstancesBtnMouseClicked(evt);
            }
        });

        ClassNameTF.setText(resourceMap.getString("ClassNameTF.text")); // NOI18N
        ClassNameTF.setName("ClassNameTF"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        NumberOfInstancesTF.setText(resourceMap.getString("NumberOfInstancesTF.text")); // NOI18N
        NumberOfInstancesTF.setName("NumberOfInstancesTF"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        ExitBtn.setText(resourceMap.getString("ExitBtn.text")); // NOI18N
        ExitBtn.setName("ExitBtn"); // NOI18N
        ExitBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ExitBtnMouseClicked(evt);
            }
        });

        NumberOfInstanceRequiredTF.setText(resourceMap.getString("NumberOfInstanceRequiredTF.text")); // NOI18N
        NumberOfInstanceRequiredTF.setName("NumberOfInstanceRequiredTF"); // NOI18N

        PauseBtn.setText(resourceMap.getString("PauseBtn.text")); // NOI18N
        PauseBtn.setName("PauseBtn"); // NOI18N
        PauseBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                PauseBtnMouseClicked(evt);
            }
        });

        StopBtn.setText(resourceMap.getString("StopBtn.text")); // NOI18N
        StopBtn.setName("StopBtn"); // NOI18N
        StopBtn.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                StopBtnMouseClicked(evt);
            }
        });

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        StartIndexTF.setText(resourceMap.getString("StartIndexTF.text")); // NOI18N
        StartIndexTF.setName("StartIndexTF"); // NOI18N

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        StopIndexTF.setText(resourceMap.getString("StopIndexTF.text")); // NOI18N
        StopIndexTF.setName("StopIndexTF"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(KBfileTF, 0, 0, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(NumberOfInstanceRequiredTF, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(StartIndexTF, javax.swing.GroupLayout.DEFAULT_SIZE, 152, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(LoadKBBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(GenerateKBBtn)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(StopIndexTF, javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(PauseBtn)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(StopBtn)))))
                            .addComponent(jLabel7, javax.swing.GroupLayout.Alignment.LEADING)))
                    .addComponent(jLabel3)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(NumberOfInstancesTF, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE)
                            .addComponent(ClassNameTF, javax.swing.GroupLayout.DEFAULT_SIZE, 215, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(ExitBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(CountInstancesBtn)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 497, Short.MAX_VALUE))
                .addGap(33, 33, 33))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(KBfileTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(LoadKBBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(GenerateKBBtn)
                    .addComponent(NumberOfInstanceRequiredTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(PauseBtn)
                    .addComponent(StopBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(StartIndexTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(StopIndexTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ClassNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(CountInstancesBtn))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(NumberOfInstancesTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ExitBtn))
                .addContainerGap(34, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ExitBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ExitBtnMouseClicked
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_ExitBtnMouseClicked

    private void LoadKBBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_LoadKBBtnMouseClicked
        // TODO add your handling code here:

        Collection errors = new ArrayList();
        try{
            Date d1=new Date();
            this.prj = Project.loadProjectFromFile(KBfileTF.getText().trim(),errors);
            this.kb=this.prj.getKnowledgeBase();
            Collection col = kb.getInstances();
            long lTotalInstances = col.size();
            Date d2=new Date();
             LoggingMessageTA.append("Project has "+lTotalInstances+" instances. Loaded in "
                    +(d2.getTime()-d1.getTime())+" ms\n");
            theLogger.info("Project has "+lTotalInstances+" instances. Loaded in "
                    +(d2.getTime()-d1.getTime())+" ms");
        }catch (Exception e){
            theLogger.severe("Load project:"+sProjectFullPath+" failed: "+e.toString());
        }
    }//GEN-LAST:event_LoadKBBtnMouseClicked

    private void CountInstancesBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_CountInstancesBtnMouseClicked
        // TODO add your handling code here:
        NumberOfInstancesTF.setText(Long.toString(InstancesCount()));
        
    }//GEN-LAST:event_CountInstancesBtnMouseClicked

    public void updateLoggingMessage(String str){
        LoggingMessageTA.append(str+"\n");
        
    }
    private void GenerateKBBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_GenerateKBBtnMouseClicked

	String sPrjFile = KBfileTF.getText().trim();   
	 String sNum=NumberOfInstanceRequiredTF.getText().trim();
        long lTotalInstanceTobeGenerated = Long.parseLong(sNum);

        long lStartFromInstance = Long.parseLong(StartIndexTF.getText().trim());
        long lUntilInstance = Long.parseLong(StopIndexTF.getText().trim());


        // private GenerateKBThread genThread=null;
        //private Thread thr = null;
        try{
	genThread = new GenerateKBThread (this, sPrjFile,
            lTotalInstanceTobeGenerated,lStartFromInstance, lUntilInstance);
	thr =new Thread(genThread);
	thr.start();
        LoggingMessageTA.append("Generating instances ...\n");
        }catch (Exception e){
            LoggingMessageTA.append("Generating thread failed! Check log");
        }
	


    }//GEN-LAST:event_GenerateKBBtnMouseClicked

    private void PauseBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_PauseBtnMouseClicked
        // TODO add your handling code here:
        LoggingMessageTA.setText("Not implemented !");
    }//GEN-LAST:event_PauseBtnMouseClicked

    private void StopBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_StopBtnMouseClicked
        // TODO add your handling code here:
        genThread.StopThread(true);
        LoggingMessageTA.append(" Thread stoped ...");
        
    }//GEN-LAST:event_StopBtnMouseClicked

    private long InstancesCount(){

        String sIname=ClassNameTF.getText().trim();
        long lNumberOfInstance = 0;
        if (sIname.length()>0){
            String sClassName=ClassNameTF.getText();
            try{
                Cls cls=kb.getCls(sClassName);
                Collection colInstances=kb.getInstances(cls);
                lNumberOfInstance =  colInstances.size();
            }catch(Exception e){
                theLogger.severe("Class not found");
            }

        }else {
            try{
                Collection colInstances=kb.getInstances();
                lNumberOfInstance =colInstances.size();
            }catch(Exception e){
                theLogger.severe("Class not found");
            }

        }
        return lNumberOfInstance;
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                GenerateKB dialog = new GenerateKB(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField ClassNameTF;
    private javax.swing.JButton CountInstancesBtn;
    private javax.swing.JButton ExitBtn;
    private javax.swing.JButton GenerateKBBtn;
    private javax.swing.JTextField KBfileTF;
    private javax.swing.JButton LoadKBBtn;
    private javax.swing.JTextArea LoggingMessageTA;
    private javax.swing.JTextField NumberOfInstanceRequiredTF;
    private javax.swing.JTextField NumberOfInstancesTF;
    private javax.swing.JButton PauseBtn;
    private javax.swing.JTextField StartIndexTF;
    private javax.swing.JButton StopBtn;
    private javax.swing.JTextField StopIndexTF;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

}
